import fs from "node:fs";
import ResponseUtil from "../../request/ResponseUtil";
import http from "node:http";
import FileUtil from "../../utils/FileUtil";
import path from "node:path";

class ActionStaticResolver {

    resolve(staticRoute: string, response: http.ServerResponse) {
        if (!staticRoute) {
            return ''
        }
        if (!fs.existsSync(staticRoute)) {
            ResponseUtil.writeNotFound(response)
        }
        const extname = path.extname(staticRoute)
        if (extname.toLowerCase() === '.html') {
            ResponseUtil.setHeaderContentTypeHtml(response)
        } else if (extname.toLowerCase() === '.js') {
            ResponseUtil.setHeaderContentTypeJS(response)
        } else if (extname.toLowerCase() === '.css') {
            ResponseUtil.setHeaderContentTypeCss(response)
        } else if (extname.toLowerCase() === '.json') {
            ResponseUtil.setHeaderContentTypeJSON(response)
        }
        return FileUtil.read(staticRoute)
    }

    resolveAndResponse(staticRoute: string, response: http.ServerResponse) {
        const staticContent = this.resolve(staticRoute, response);
        response.end(staticContent);
    }
}

export default new ActionStaticResolver();
